package org.nmgyjt.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.CsSystemIDSelectBean;
import org.nmgyjt.springboot.beans.admin.CsSystemSourcePreSetInfo;
import org.nmgyjt.springboot.beans.admin.StatisticBean;
import org.nmgyjt.springboot.entity.admin.*;
import org.nmgyjt.springboot.entity.protectTarget.ProtectTargetInfo;
import org.nmgyjt.springboot.entity.refuge.RefugeInfo;
import org.nmgyjt.springboot.mapper.CsSystemAdminMapper;
import org.nmgyjt.springboot.mapper.CsSystemSourcePreSetInfoMapper;
import org.nmgyjt.springboot.mapper.ExpertMapper;
import org.nmgyjt.springboot.mapper.ProtectTargetMapper;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.ZWWXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProtectTargetServiceImpl extends ServiceImpl<ProtectTargetMapper, ProtectTargetInfo> implements ProtectTargetService {

    @Autowired
    private ProtectTargetMapper protectTargetMapper;

    @Autowired
    private ICsSystemSourcePreSetInfoService iCsSystemSourcePreSetInfoService;
    @Autowired
    CsSystemAdminMapper csSystemAdminMapper;
    @Autowired
    ZWWXUtils zwwxUtils;
    @Autowired
    ICsSystemSourceTypeService sourceTypeService;


    @Override
    public ProtectTargetInfo getByDepId(String depId) {
        QueryWrapper<ProtectTargetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state", "1");
        ProtectTargetInfo protectTargetInfo = null;
        try {
            protectTargetInfo = protectTargetMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(protectTargetInfo)) {
                return protectTargetInfo;
            }
//            else{
//                ProtectTargetInfo protectTargetInfo1=new ProtectTargetInfo();
//                CsSystemIDSelectBean csSystemIDSelectBean=new CsSystemIDSelectBean();
//                csSystemIDSelectBean.setId(depId);
//                CsSystemDeptResponse detailCsSystemOrg=iCsSystemDeptService.detailCsSystemOrg(csSystemIDSelectBean);
//                if(!ObjectUtils.isEmpty(detailCsSystemOrg)){
//                    protectTargetInfo1.setProtectName(detailCsSystemOrg.getName());
//                    protectTargetInfo1.setProtectType(detailCsSystemOrg.getSourceType());
//                }
//                return protectTargetInfo1;
//            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return protectTargetInfo;
    }

    @Override
    public Map<String, Object> getProtectTargetStatistics(StatisticBean statisticBean) {
        Map<String, Object> retMap = new LinkedHashMap<>();
        QueryWrapper<CsSystemAdmin> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(statisticBean.getCreatedBy())) {
            queryWrapper.eq("phone", statisticBean.getCreatedBy());
            queryWrapper.eq("superior_org", statisticBean.getSuperOrgId());
        }else{
            queryWrapper.eq("org_id", statisticBean.getSuperOrgId());
        }
        queryWrapper.orderByDesc("id").last("limit 1");
//        queryWrapper.eq("menu_id", statisticBean.getMenuId());
        CsSystemAdmin csSystemAdmin = csSystemAdminMapper.selectOne(queryWrapper);
//        if (ObjectUtils.isEmpty(csSystemAdmin)) {
//            return retMap;
//        }
        String sql = " AND r.state <> '1'";
        if (StringUtils.isNotEmpty(statisticBean.getCreatedBy())) {
            sql = sql + " AND a.superior_org='" + csSystemAdmin.getOrgId() + "'";
        } else {
            sql = sql + " AND a.superior_org='-1'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getName())) {
            sql = sql + " AND a.org_name like '%" + statisticBean.getName() + "%'";
        }
//        if (StringUtils.isNotEmpty(statisticBean.getType())) {
//            JSONArray jsonArray = JSON.parseArray(statisticBean.getType());
//            String type = jsonArray.getString(jsonArray.size() - 1);
////            if("15130100".equals(type)||"15131100".equals(type)||
////                    "15131200".equals(type)||"15131500".equals(type)){
////                sql = sql + " AND r.second_type_code like '%"+type+"%'";
////            }else{
//                sql = sql + " AND ext.source_type like '%" + type + "%'";
////            }
//        }
        String sql2 = "";
        if (StringUtils.isNotEmpty(statisticBean.getStatus())) {
            if ("1".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '0' ";
            }
            if ("2".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '2' ";
            }

        }
        List<Map<String, Object>> List = protectTargetMapper.statisticProtectTarget(sql, sql2);
        Integer protectTargetCount = protectTargetMapper.statisticProtectTargetCount(csSystemAdmin.getOrgId());
        Integer protectTargetTypeCount = protectTargetMapper.statisticProtectTargetTypeCount(csSystemAdmin.getOrgId());

        List<Map<String, Object>> countTypeList = new ArrayList<>();
        queryWrapper.clear();
        queryWrapper.eq("org_id", statisticBean.getSuperOrgId()).orderByDesc("id").last("limit 1");
        CsSystemAdmin bean = csSystemAdminMapper.selectOne(queryWrapper);
        CsSystemSourcePreSetInfo preSetInfo = iCsSystemSourcePreSetInfoService.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, bean.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, "1000000012").orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
        CsSystemSourcePreSetInfoResponse infoResponse = new CsSystemSourcePreSetInfoResponse();
        List<CsSystemSourceType> sourceTypes1 = new ArrayList<>();
        infoResponse.setMenuId(bean.getMenuId());
        infoResponse.setOrgId(bean.getOrgId());
        if (null != preSetInfo) {
            List<String> preSetData = JSONObject.parseObject(preSetInfo.getPreSetTypes(), List.class);
            if (!CollectionUtils.isEmpty(preSetData)) {
                for (Object strObj : preSetData) {
                    String str = strObj.toString();
                    List<String> list = Arrays.asList(str.replace("\"[", "").replace("]\"", "").replace("[", "").replace("]", "").replace("\"", "").split(","));
                    sourceTypes1.add(sourceTypeService.getById(list.get(list.size() - 1)));
                }

            }
        }
//        Map<String, Object> map15130100 = new HashMap<>();
//        String type15130100 = "";
//        String code15130100 = "";
//        int done15130100 = 0;
//        int allNum15130100 = 0;
//        int undone15130100 = 0;
//
//        Map<String, Object> map15131100 = new HashMap<>();
//        String type15131100 = "";
//        String code15131100 = "";
//        int done15131100 = 0;
//        int allNum15131100 = 0;
//        int undone15131100 = 0;
//
//        Map<String, Object> map15131200 = new HashMap<>();
//        String type15131200 = "";
//        String code15131200 = "";
//        int done15131200 = 0;
//        int allNum15131200 = 0;
//        int undone15131200 = 0;
//
//        Map<String, Object> map15131500 = new HashMap<>();
//        String type15131500 = "";
//        String code15131500 = "";
//        int done15131500 = 0;
//        int allNum15131500 = 0;
//        int undone15131500 = 0;

        for (CsSystemSourceType csSystemSourceType : sourceTypes1) {
            Map<String, Object> countType = protectTargetMapper.statisticProtectTargetTypeCountStatus(csSystemAdmin.getOrgId(), csSystemSourceType.getId());
            Map<String, Object> map = new HashMap<>();

            map.put("second_type", csSystemSourceType.getName());
            map.put("second_type_code", csSystemSourceType.getId());
            if (null == countType || countType.isEmpty()) {
                map.put("done", 0);
                map.put("allNum", 0);
                map.put("undone", 0);
                countTypeList.add(map);
            } else {
                map.put("done", countType.get("done") == null ? 0 : countType.get("done"));
                map.put("allNum", countType.get("allNum") == null ? 0 : countType.get("allNum"));
                map.put("undone", countType.get("undone") == null ? 0 : countType.get("undone"));
                countTypeList.add(map);
            }
//            if (!"15130000".equals(csSystemSourceType.getParentId())) {
//                CsSystemSourceType systemSourceType = sourceTypeService.getById(csSystemSourceType.getParentId());
//                if ("15130100".equals(csSystemSourceType.getParentId())) {
//                    type15130100 = systemSourceType.getName();
//                    code15130100 = systemSourceType.getId();
//                    done15130100 = done15130100 + Integer.valueOf(String.valueOf(countType.get("done")));
//                    allNum15130100 = allNum15130100 + Integer.valueOf(String.valueOf(countType.get("allNum")));
//                    undone15130100 = undone15130100 + Integer.valueOf(String.valueOf(countType.get("undone")));
//                }
//                if ("15131100".equals(csSystemSourceType.getParentId())) {
//                    type15131100 = systemSourceType.getName();
//                    code15131100 = systemSourceType.getId();
//                    done15131100 = done15131100 + Integer.valueOf(String.valueOf(countType.get("done")));
//                    allNum15131100 = allNum15131100 + Integer.valueOf(String.valueOf(countType.get("allNum")));
//                    undone15131100 = undone15131100 + Integer.valueOf(String.valueOf(countType.get("undone")));
//                }
//                if ("15131200".equals(csSystemSourceType.getParentId())) {
//                    type15131200 = systemSourceType.getName();
//                    code15131200 = systemSourceType.getId();
//                    done15131200 = done15131200 + Integer.valueOf(String.valueOf(countType.get("done")));
//                    allNum15131200 = allNum15131200 + Integer.valueOf(String.valueOf(countType.get("allNum")));
//                    undone15131200 = undone15131200 + Integer.valueOf(String.valueOf(countType.get("undone")));
//                }
//                if ("15131500".equals(csSystemSourceType.getParentId())) {
//                    type15131500 = systemSourceType.getName();
//                    code15131500 = systemSourceType.getId();
//                    done15131500 = done15131500 + Integer.valueOf(String.valueOf(countType.get("done")));
//                    allNum15131500 = allNum15131500 + Integer.valueOf(String.valueOf(countType.get("allNum")));
//                    undone15131500 = undone15131500 + Integer.valueOf(String.valueOf(countType.get("undone")));
//                }
//            }
        }
//        if (!"".equals(code15130100)) {
//            map15130100.put("second_type", type15130100);
//            map15130100.put("second_type_code", code15130100);
//            map15130100.put("done", done15130100);
//            map15130100.put("allNum", allNum15130100);
//            map15130100.put("undone", undone15130100);
//            countTypeList.add(map15130100);
//
//        }
//        if (!"".equals(type15131100)) {
//            map15131100.put("second_type", type15131100);
//            map15131100.put("second_type_code", code15131100);
//            map15131100.put("done", done15131100);
//            map15131100.put("allNum", allNum15131100);
//            map15131100.put("undone", undone15131100);
//            countTypeList.add(map15131100);
//        }
//        if (!"".equals(type15131200)) {
//            map15131200.put("second_type", type15131200);
//            map15131200.put("second_type_code", code15131200);
//            map15131200.put("done", done15131200);
//            map15131200.put("allNum", allNum15131200);
//            map15131200.put("undone", undone15131200);
//            countTypeList.add(map15131200);
//        }
//        if (!"".equals(type15131500)) {
//            map15131500.put("second_type", type15131500);
//            map15131500.put("second_type_code", code15131500);
//            map15131500.put("done", done15131500);
//            map15131500.put("allNum", allNum15131500);
//            map15131500.put("undone", undone15131500);
//            countTypeList.add(map15131500);
//        }
        countTypeList.sort(Comparator.comparingInt(o -> Integer.parseInt(o.get("second_type_code").toString())));
        retMap.put("protectTargetTypeCount", protectTargetTypeCount);
        retMap.put("protectTargetCount", protectTargetCount);
        retMap.put("countTypeList", countTypeList);
        retMap.put("list", List);
        return retMap;
    }

    public Boolean deleteByDepId(String depId) {
        QueryWrapper<ProtectTargetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state", "1");
        ProtectTargetInfo protectTargetInfo = protectTargetMapper.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(protectTargetInfo)) {
            int num = protectTargetMapper.deleteByDepId(protectTargetInfo.getDepId());
            if (num > 0) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    @Override
    public void snycZwwxByHeadPhone() {
        QueryWrapper<ProtectTargetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("first_head_phone");
        queryWrapper.ne("first_snyc_state", "0");
        List<ProtectTargetInfo> protectTargetInfoListFirst = protectTargetMapper.selectList(queryWrapper);
        for (ProtectTargetInfo protectTargetInfo : protectTargetInfoListFirst) {
            String ssoAccessToken = zwwxUtils.getGovWxToken();
            Integer code = zwwxUtils.getZWUserInfo(protectTargetInfo.getFirstHeadPhone(), "protect-unit-detail/index?depId=" + protectTargetInfo.getDepId(), ssoAccessToken);
            protectTargetInfo.setFirstSnycState(code.toString());
            this.saveOrUpdate(protectTargetInfo);
        }
        queryWrapper.clear();
        queryWrapper.isNotNull("dep_head_phone");
        queryWrapper.ne("dep_snyc_state", "0");
        List<ProtectTargetInfo> protectTargetInfoListDep = protectTargetMapper.selectList(queryWrapper);
        for (ProtectTargetInfo protectTargetInfo : protectTargetInfoListDep) {
            String ssoAccessToken = zwwxUtils.getGovWxToken();
            Integer code = zwwxUtils.getZWUserInfo(protectTargetInfo.getDepHeadPhone(), "protect-unit-detail/index?depId=" + protectTargetInfo.getDepId(), ssoAccessToken);
            protectTargetInfo.setDepSnycState(code.toString());
            this.saveOrUpdate(protectTargetInfo);
        }
        queryWrapper.clear();
        queryWrapper.isNotNull("org_head_phone");
        queryWrapper.ne("org_snyc_state", "0");
        List<ProtectTargetInfo> protectTargetInfoListOrg = protectTargetMapper.selectList(queryWrapper);
        for (ProtectTargetInfo protectTargetInfo : protectTargetInfoListOrg) {
            String ssoAccessToken = zwwxUtils.getGovWxToken();
            Integer code = zwwxUtils.getZWUserInfo(protectTargetInfo.getOrgHeadPhone(), "protect-unit-detail/index?depId=" + protectTargetInfo.getDepId(), ssoAccessToken);
            protectTargetInfo.setOrgSnycState(code.toString());
            this.saveOrUpdate(protectTargetInfo);
        }
    }
}
